<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>

    var reorderSpaces = function (text) {
      let emptys = 0
      text.replace(/\s/g, () => emptys++)
      let list = text.match(/\w+/g)
      let n = emptys / (list.length - 1) | 0
      let s = ' '.repeat(n)
      return list.join(s) + ' '.repeat(emptys - n * (list.length - 1))
    };
    console.log(reorderSpaces("  this   is  a sentence "));
  </script>
</body>

</html>